package com.test.session;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.pojo.Product;

/**
 * @description getcurrentsession需要放在事务里
 * @author Leon Plious
 * @date 2020年7月6日
 */
public class HibernateTestGetCurrentSession {

	public static void main(String[] args) {
		
		// 不在事务里会报错如下
		// Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		Product product = (Product) session.get(Product.class, 1);
		
		// session.getTransaction().commit();之后，关闭session的话报错，固无需关闭session
		// Exception in thread "main" org.hibernate.SessionException: Session was already closed
		session.getTransaction().commit();
		session.close();
	}
}
